//
//  VideoDataDecode.swift
//  微信小视频
//
//  Created by 罗杰 on 2016/11/12.
//  Copyright © 2016年 罗杰. All rights reserved.
//

import UIKit
import AVFoundation
class VideoDataDecode: NSObject {
    var videoPath:String
    
    func getImageSource(completion:@escaping (([UIImage]) -> Void)){
        let queue:DispatchQueue = DispatchQueue.global(qos: .default)
        let mainQueeu = DispatchQueue.main
        queue.async { 
            self.assertReader?.startReading()
          let images = self.getBufferData(assertReader: self.assertReader!, videoAssertTrackOuput: self.videoAssetTrackOutput!)
         
          mainQueeu.async(execute: {
           completion(images)
          })
           
        
        }
    
    
    
    
    }
    
    
    private var assertReader:AVAssetReader?
    private var videoAssetTrackOutput:AVAssetReaderTrackOutput?
    private var buffer:CMSampleBuffer?
    init(videoPath:String) {
        
        self.videoPath = videoPath
        super.init()
        
        assert(!videoPath.contains("http"), "url只能是本地视频")
        
        let asset = AVAsset(url: URL(fileURLWithPath: videoPath))
        print(CMTimeGetSeconds(asset.duration))
        do {
        let assertReader: AVAssetReader =  try AVAssetReader(asset: asset)
            self.assertReader=assertReader
        let assertVideoTrack:AVAssetTrack = asset.tracks(withMediaType: AVMediaTypeVideo).first!
        let videoAssetTrackOutput = AVAssetReaderTrackOutput(track: assertVideoTrack, outputSettings: nil)
           self.videoAssetTrackOutput=videoAssetTrackOutput
        if assertReader.canAdd(videoAssetTrackOutput) {
            assertReader.add(videoAssetTrackOutput)
        }else {
            assert(false, "设置失败")
        }
            
        } catch let error as NSError{
          print(error)
        
        }
     
        
    }
    
    private func getBufferData(assertReader:AVAssetReader, videoAssertTrackOuput:AVAssetReaderTrackOutput) -> [UIImage]{
        var imageArray:[UIImage]=[];
        while assertReader.status == AVAssetReaderStatus.reading && videoAssertTrackOuput.track.nominalFrameRate>0 {
             buffer = videoAssertTrackOuput.copyNextSampleBuffer()
           let image = UIImage.imageWithSampleBuffer(sampleBuffer: buffer!)
           imageArray.append(image)
        }
        assertReader.cancelReading()
        return imageArray
    
    }
    deinit {
        print("释放")
    }
    
    

}
